package com.example.administrator.puzzlepic;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.administrator.puzzlepic.com.xiaoxu.util.GetPicUtil;
import com.example.administrator.puzzlepic.com.xiaoxu.util.ScreenUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TextView selectMode;//标题
    View diffTypePopup;//困难类型的popup
    PopupWindow mPopup;

    //View picFromPopup;//图片选择方式popup
    GridView mGridView;//显示提供图片的grid

    List<Bitmap> dataList = new ArrayList<>();//数据源

    GridAdapter mGridAdapter;
    int density;//像素密度
    private static final int RESULT_IMAGE = 100;
    private static final int RESULT_CAMERA = 200;
    //照片的路径
    public static String TEMP_IMAGE_PATH = Environment.getExternalStorageDirectory().getPath() + "/temp.png";

    private int mType = 2;

    int[] bitmapId = new int[]{R.mipmap.i1, R.mipmap.i2,
            R.mipmap.i3, R.mipmap.i4, R.mipmap.i5, R.mipmap.i6, R.mipmap.i7, R.mipmap.i8, R.mipmap.i9,
            R.mipmap.i10, R.mipmap.i11, R.mipmap.i12, R.mipmap.i13, R.mipmap.i14, R.mipmap.i15, R.mipmap.i16};

    //初始化
    private void initView() {

        selectMode = (TextView) findViewById(R.id.select_mode);
        diffTypePopup = LayoutInflater.from(this).inflate(R.layout.type_popup, null);
        //picFromPopup = LayoutInflater.from(this).inflate(R.layout.pic_from_popup,null);

        mGridView = (GridView) findViewById(R.id.gv_puzzle_main_pic);

        density = (int) ScreenUtil.getDeviceDensity(this);

        mGridAdapter = new GridAdapter(this, R.layout.mydefined, dataList);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        addList();
        selectMode.setOnClickListener(listener);
        mGridView.setAdapter(mGridAdapter);
        // gridListener();//对最后一个进行监听
        //对popup的点击监听
        addPopupListener();
        //对GridView监听
        addGvListener();

    }

    private void addPopupListener() {
        TextView ty1 = (TextView) diffTypePopup.findViewById(R.id.type_1);
        TextView ty2 = (TextView) diffTypePopup.findViewById(R.id.type_2);

        ty1.setOnTouchListener(popTouchListener);
        ty2.setOnTouchListener(popTouchListener);

    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.select_mode:

                    popupShow(selectMode);

                    break;
            }
        }
    };


    //困难模式的pop显示
    private void popupShow(View selectMode) {

        mPopup = new PopupWindow(diffTypePopup, 60 * density, 100 * density);

        mPopup.setBackgroundDrawable(new ColorDrawable(Color.GRAY));

        mPopup.setFocusable(true);
        mPopup.setOutsideTouchable(true);

        mPopup.showAsDropDown(selectMode);


    }

    //GridView的点击事件
    private void addGvListener() {
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < bitmapId.length - 1) {

                    Intent intent = new Intent(MainActivity.this, PuzzleActivity.class);
                    intent.putExtra("getPicWay", 3);
                    intent.putExtra("resId", bitmapId[position]);
                    intent.putExtra("mType", mType);

                    MainActivity.this.startActivity(intent);

                } else {
                    //图片来自  本地相册 /拍照
                    if (position == dataList.size() - 1) {
                        final CharSequence[] items = {"手机相册", "相机拍摄"};
                        AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle("选择图片")
                                .setIcon(R.drawable.choosepic)
                                .setItems(items, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        if (which == 0) {

                                            getNativePhoto();

                                        } else if (which == 1) {

                                            takePhoto();
                                        }

                                    }
                                }).create();

                        dialog.show();

                    }

                }


            }
        });


    }


    //popup菜单的点击事件
    private View.OnTouchListener popTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (v.getId()) {
                case R.id.type_1:

                    mType = 3;
                    selectMode.setText(" 3 * 3 ");
                    selectMode.invalidate();

                    popDisMiss();
                    break;
                case R.id.type_2:

                    mType = 4;
                    selectMode.setText(" 4 * 4 ");
                    selectMode.invalidate();

                    popDisMiss();//popup消失
                    break;

            }

            return false;
        }
    };


    private void popDisMiss() {

        if (mPopup.isShowing()) {

            mPopup.dismiss();

        }

    }

    void addList() {
        for (int i = 0; i < bitmapId.length; i++) {

            dataList.add(BitmapFactory.decodeResource(getResources(), bitmapId[i]));

        }


    }

    void gridListener() {

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            //view 就是当前点击的view。
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == dataList.size() - 1) {

                    final CharSequence[] items = {"手机相册", "相机拍摄"};
                    AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle("选择图片")
                            .setIcon(R.drawable.choosepic)
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    if (which == 0) {

                                        getNativePhoto();

                                    } else if (which == 1) {

                                        takePhoto();
                                    }

                                }
                            }).create();

                    dialog.show();

                }
            }
        });


    }

    private void takePhoto() {

        GetPicUtil.takePhoto(MainActivity.this);

    }

    private void getNativePhoto() {

        GetPicUtil.getNativePic(MainActivity.this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_IMAGE && data != null) {
                //mType = 1;
                //相册
                Cursor cursor = this.getContentResolver().query(data.getData(), null, null, null, null);
                cursor.moveToFirst();

                String imagePath = cursor.getString(cursor.getColumnIndex("_data"));
                Intent intent = new Intent(MainActivity.this, PuzzleActivity.class);
                intent.putExtra("imagePath", imagePath);
                intent.putExtra("mType", mType);
                intent.putExtra("getPicWay", 1);

                Log.d("MainActivity", "  " + imagePath + "--- " + mType);

                startActivity(intent);


            } else if (requestCode == RESULT_CAMERA) {

                //相机

                Intent intent = new Intent(MainActivity.this, PuzzleActivity.class);
                intent.putExtra("mPicPath", TEMP_IMAGE_PATH);

                intent.putExtra("mType", mType);
                intent.putExtra("getPicWay", 2);

                startActivity(intent);

            }


        }


    }
}
